/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rhserver;

import Entities.Activereservation;
import helpers.Debug;
import java.util.*;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;

/**
 *
 * @author Bari
 */
public class TimerManager {

    private Timer timer;
    private Map<Long, ResourceDeactivateTask> timerTasks;

    public TimerManager() {
        //One Timer object, all task execute on the same secondary thread -> for optimal performance
        timer = new Timer("ResourceTimer", false);
        timerTasks = new HashMap<Long, ResourceDeactivateTask>();
    }

    public void startResouceTimer(long actiovationLength, long reservationId) {
        ResourceDeactivateTask task = new ResourceDeactivateTask(reservationId);

        if (timerTasks.containsKey(reservationId)) {
            timerTasks.get(reservationId).cancel();
            timerTasks.remove(reservationId);
        }

        timer.schedule(task, actiovationLength);
        timerTasks.put(reservationId, task);
    }
    
    public void restartTimersAfterDB()
    {
        RestartTimersDelayed task=new RestartTimersDelayed();
        timer.schedule(task, 1000);
        
    }
    
    class RestartTimersDelayed extends TimerTask{

        @Override
        public void run() {
         EntityManager em = MainController.getInstance().getEntityManager();
         TypedQuery<Activereservation> query = em.createNamedQuery("Activereservation.findAll", Activereservation.class);
         List<Activereservation> reservations=query.getResultList();
         EntityTransaction tx = em.getTransaction();
         Date currentDate=MainController.getInstance().getCurrentDate();
         for ( Activereservation reservation : reservations )
         {
             if (reservation.getEndtime().getTime()-currentDate.getTime()<1000*60)//difference is smaller than a minute
             {
                    tx.begin();
                    em.remove(reservation);
                    tx.commit();
                    MainController.getInstance().smsStopResource(reservation.getResource());
                    MyLogger.logResourceStop(reservation.getResource(), currentDate,em);
             }
             else
             {
                 startResouceTimer(reservation.getEndtime().getTime()-currentDate.getTime(), reservation.getId());
                 Debug.logMessage("restartTimersAfterDB", "restarting for resource: "+reservation.getResource().getName());
             }
         }
        }
    }
    
    

    class ResourceDeactivateTask extends TimerTask {

        private long reservationId;

        ResourceDeactivateTask(long reservationId) {
            this.reservationId = reservationId;
        }

        @Override
        public void run() {
            EntityManager em = MainController.getInstance().getEntityManager();
            TypedQuery<Activereservation> query = em.createNamedQuery("Activereservation.findById", Activereservation.class);
            query.setParameter("id", reservationId);
            List<Activereservation> reservations = query.getResultList();
            if (reservations.size() > 0) {
                Activereservation reservation = reservations.get(0);
                Debug.logMessage("ResourceDeactivateTask", "Deactivating resource: " + reservation.toString());
                Date deactivationDate = reservation.getEndtime();
                Date currentDate = MainController.getInstance().getCurrentDate();
                if (currentDate.getTime() - deactivationDate.getTime() < 1000 * 60)//difference is smaller than a minute
                {
                    //TODO send deactivation SMS
                    EntityTransaction tx = em.getTransaction();
                    tx.begin();
                    em.remove(reservation);
                    tx.commit();
                    MainController.getInstance().smsStopResource(reservation.getResource());
                    MyLogger.logResourceStop(reservation.getResource(), currentDate,em);
                }
            } else {
                Debug.logError("ResourceDeactivateTask", "reservation with id: " + reservationId + " not found");
            }
            em.close();
            timerTasks.remove(reservationId);

        }
    }
}
